from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from .models import User
from GlobalFunction.utils import get_post_json_param
from GlobalFunction.GlobalData import *
import json

# Create your views here.
# 这里是一段学习的时候用的废物代码
# def userLogin(request):
#     formula = request.GET['formula']
#     try:
#         result = eval(formula, {})
#     except:
#         result = 'Error formula'
#     return HttpResponse(result)

def addUser(request):
    #注意这里不能直接用=,会制造引用
    result = RETURN_SUCCESS.copy()
    try:
        (name, openid, idNum) = get_post_json_param(request, 'name', 'openid', 'idNum')
        user_list = User.objects.filter(openid=openid)
        if(len(user_list)==0):
            newUser = User(name=name, openid=openid, idNum=idNum, grade=-1)
            newUser.save()
        else:
            result['msg'] = 'User exists!'
    except Exception as err:
        result = RETURN_FAILED
        result['err_msg'] = str(err)
    return JsonResponse(result)

def getUserInfo(request):
    result = RETURN_SUCCESS.copy()
    result['is_exist'] = False
    try:
        [openid] = get_post_json_param(request, 'openid')
        user_list = User.objects.filter(openid=openid)
        if(len(user_list)==1):
            result['userName'] = user_list[0].name
            result['grade'] = user_list[0].grade
            result['idNum'] = user_list[0].idNum
            result['is_exist'] = True
    except Exception as err:
        result = RETURN_FAILED
        result['err_msg'] = str(err)
    return JsonResponse(result)